<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
              <j-search-select-tag v-model="model.brand" dict="ene_formula_pg_base,fc_no,id"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="fcNo" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fcNo">
              <j-search-select-tag v-model="model.fcNo" dict="ene_formula_pg_base,formula_name,id"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="a材料" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
              <j-search-select-tag v-model="model.eneFormulaPgFrontIngredientDetails[0].ingredientName" dict="ene_ingredient_management,material_description,id" disabled  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="b材料" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
              <j-search-select-tag v-model="model.eneFormulaPgFrontIngredientDetails[1].ingredientName" dict="ene_ingredient_management,material_description,id" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="比例值A" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proportionA">
              <a-input-number v-model="model.proportionA" placeholder="请输入比例值A" style="width: 100%" @change="computeFcRatio()"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="比例值B" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proportionB">
              <a-input-number v-model="model.proportionB" placeholder="请输入比例值B" style="width: 100%" @change="computeFcRatio()"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item :labelCol="labelCol3" :wrapperCol="wrapperCol3">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
                <div class='mark-infos' style="table-layout: fixed;">
                  <a-table
                    ref="markTable"
                    size="middle"
                    :scroll="{x:false,y:false}"
                    bordered
                    :rowKey="(record = () => record.id)"
                    :columns="columns"
                    :dataSource="model.eneFormulaPgFrontIngredientDetails"
                    :pagination="false"
                    :loading="loading"
                    class="j-table-force-nowrap1">
                    <template v-for="col in ['ingredientId','ingredientName','fcRatio','batchIngredient','batchIngredientLow','batchIngredientUp']" :slot="col" slot-scope="text, record,index">
                      <div :key="record.id">
                        <a-form-model-item  v-if="col==='ingredientName'">
                          <j-search-select-tag v-model="record.ingredientName"
                                               dict="ene_ingredient_management,material_description,id"
                                               placeholder="请输入原料名称"
                                               :key="index"
                                               @change="index===0 ? searchFcRatio(record):computeFcRatio()"
                                               :getPopupContainer="getPopupContainer"

                          />
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='ingredientId'"  >
                          <a-input v-model="record.ingredientId" placeholder="请输入原料编号" disabled />
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='fcRatio'">
                          <a-input
                            v-model="record.fcRatio"
                            placeholder="请输入配方卡比例"
                            disabled
                          />
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='batchIngredient'" >
                          <a-input v-model="record.batchIngredient" disabled></a-input>
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='batchIngredientLow'">
                          <a-input v-model="record.batchIngredientLow" disabled
                          />
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='batchIngredientUp'" >
                          <a-input v-model="record.batchIngredientUp" disabled/>
                        </a-form-model-item>
                      </div>
                    </template>
                  </a-table>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model-item>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction, postAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import Decimal from 'decimal.js'

  export default {
    name: 'EneFormulaPgFrontIngredientForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
          brand:'',
          fcNo:'',
          eneFormulaPgFrontIngredientDetails:[
            {
              id: '',
              ingredientId: '',
              ingredientName: '',
              fcRatio: '',
              batchIngredient: '',
              batchIngredient_low: '',
              batchIngredient_up: '',
            },
            {
              id: '',
              ingredientId: '',
              ingredientName: '',
              fcRatio: '',
              batchIngredient: '',
              batchIngredient_low: '',
              batchIngredient_up: '',
            }
          ]
         },
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function(t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '原料编码',
            align: 'center',
            dataIndex: 'ingredientId',
            width: 160,
            scopedSlots: { customRender: 'ingredientId' }
          },
          {
            title: '原料名称',
            align: 'center',
            dataIndex: 'ingredientName',
            width: 160,
            scopedSlots: { customRender: 'ingredientName' },
          },
          {
            title: '配方卡比例',
            align: 'center',
            dataIndex: 'fcRatio',
            scopedSlots: { customRender: 'fcRatio' }
          },
          {
            title: '每批配料量(kg/批)',
            align: 'center',
            dataIndex: 'batchIngredient',
            width: 160,
            scopedSlots: { customRender: 'batchIngredient' }
          },
          {
            title: '每批配料量下限',
            align: 'center',
            dataIndex: 'batchIngredientLow',
            scopedSlots: { customRender: 'batchIngredientLow' }
          },
          {
            title: '每批配料量上限',
            align: 'center',
            dataIndex: 'batchIngredientUp',
            scopedSlots: { customRender: 'batchIngredientUp' }
          },
        ],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol3: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol3: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        loading: false,
        url: {
          add: "/craft/eneFormulaPgFrontIngredient/add",
          edit: "/craft/eneFormulaPgFrontIngredient/edit",
          queryById: "/craft/eneFormulaPgFrontIngredient/queryById"
        }
      }
    },
    computed: {
      validatorRules() {
        return {
          brand: { required: true, message: '请输入品牌!' },
          'eneFormulaPgFrontIngredientDetails[0].ingredientName': { required: true, message: '请输入材料！' },
          'eneFormulaPgFrontIngredientDetails[1].ingredientName': { required: true, message: '请输入材料！' },
        }
      },
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    watch:{
      'model.eneFormulaPgFrontIngredientDetails.0.fcRatio'(newVal,oldVal){
        if(newVal!==''){
          getAction('/craft/eneFormulaPgFrontIngredient/searchSlurryFactor',{
            brand:this.model.brand
          }).then((res)=>{
            if(res.success){
              let batch0 =new Decimal(res.result).times(newVal).toDecimalPlaces(2,Decimal.ROUND_HALF_UP)
              this.$set(this.model.eneFormulaPgFrontIngredientDetails[0],'batchIngredient',batch0)

              this.model.eneFormulaPgFrontIngredientDetails[1].ingredientName = this.model.eneFormulaPgFrontIngredientDetails[1].ingredientName||''
              if(this.model.eneFormulaPgFrontIngredientDetails[1].ingredientName!=='') {
                let batch1 = new Decimal(this.model.eneFormulaPgFrontIngredientDetails[0].batchIngredient)
                  .dividedBy(this.model.proportionA).times(this.model.proportionB)
                  .toDecimalPlaces(2, Decimal.ROUND_HALF_UP)
                this.$set(this.model.eneFormulaPgFrontIngredientDetails[1], 'batchIngredient', batch1)
              }
            }
          })
        }
        else {
          this.$set(this.model.eneFormulaPgFrontIngredientDetails[0],'batchIngredient',0)
        }
      },
      'model.eneFormulaPgFrontIngredientDetails.1.fcRatio'(newVal,oldVal){
        if(newVal!==''){
          this.model.eneFormulaPgFrontIngredientDetails[1].ingredientName = this.model.eneFormulaPgFrontIngredientDetails[1].ingredientName||''
          if(this.model.eneFormulaPgFrontIngredientDetails[1].ingredientName!=='') {
            let batch1 = new Decimal(this.model.eneFormulaPgFrontIngredientDetails[0].batchIngredient)
              .dividedBy(this.model.proportionA).times(this.model.proportionB)
              .toDecimalPlaces(2, Decimal.ROUND_HALF_UP)
            this.$set(this.model.eneFormulaPgFrontIngredientDetails[1], 'batchIngredient', batch1)
          }
        }
        else {
          this.$set(this.model.eneFormulaPgFrontIngredientDetails[1],'batchIngredient',0)
        }
      },
      'model.eneFormulaPgFrontIngredientDetails.0.batchIngredient'(newVal,oldVal){
        if(newVal!==''){
          let Abatch=new Decimal(0)
          let Bbatch=new Decimal(0)
          Abatch=new Decimal(newVal).times(0.95).toDecimalPlaces(2,Decimal.ROUND_HALF_UP)
          Bbatch=new Decimal(newVal).times(1.05).toDecimalPlaces(2,Decimal.ROUND_HALF_UP)
          this.$set(this.model.eneFormulaPgFrontIngredientDetails[0],'batchIngredientLow',Abatch)
          this.$set(this.model.eneFormulaPgFrontIngredientDetails[0],'batchIngredientUp',Bbatch)
        }
      },
      'model.eneFormulaPgFrontIngredientDetails.1.batchIngredient'(newVal,oldVal){
        if(newVal!==''){
          let Abatch=new Decimal(0)
          let Bbatch=new Decimal(0)
          Abatch=new Decimal(newVal).times(0.95).toDecimalPlaces(2,Decimal.ROUND_HALF_UP)
          Bbatch=new Decimal(newVal).times(1.05).toDecimalPlaces(2,Decimal.ROUND_HALF_UP)
          this.$set(this.model.eneFormulaPgFrontIngredientDetails[1],'batchIngredientLow',Abatch)
          this.$set(this.model.eneFormulaPgFrontIngredientDetails[1],'batchIngredientUp',Bbatch)
        }
      }
    },

    methods: {
      computeFcRatio() {
          this.searchIngredientId();
        this.model.eneFormulaPgFrontIngredientDetails[1].ingredientName = this.model.eneFormulaPgFrontIngredientDetails[1].ingredientName || "";
        if (this.model.eneFormulaPgFrontIngredientDetails[0].fcRatio !== ''
          && this.model.eneFormulaPgFrontIngredientDetails[1].ingredientName !== ''
          && this.model.proportionB !== ''){
            let fcRatio = new Decimal(0)
            fcRatio = new Decimal(this.model.eneFormulaPgFrontIngredientDetails[0].fcRatio)
            fcRatio = fcRatio.times(this.model.proportionB).dividedBy(this.model.proportionA).toDecimalPlaces(2,Decimal.ROUND_HALF_UP)
            this.$set(this.model.eneFormulaPgFrontIngredientDetails[1], 'fcRatio', fcRatio)
        }
        else {
          this.$set(this.model.eneFormulaPgFrontIngredientDetails[1], 'fcRatio', '')
        }
      },
      getPopupContainer(triggerNode) {
        return document.body; // 将下拉框渲染到 body 上
      },
      searchIngredientId(){
          postAction('/craft/eneFormulaPgFrontIngredient/searchIngredientId',
            this.model.eneFormulaPgFrontIngredientDetails,
          ).then(res=>{
            if(res.success){
              for(let i=0;i<res.result.length;i++){
                this.$set(this.model.eneFormulaPgFrontIngredientDetails[i], 'ingredientId', res.result[i].ingredientId);
              }
            }
          })
      },
      searchFcRatio(record) {
        if (record) {
          record.ingredientName = record.ingredientName || "";
          if (record.ingredientName !== '' && record.ingredientName !== null && this.model.brand !== null && this.model.brand !== '') {
            this.searchIngredientId()
            getAction('/craft/eneFormulaPgFrontIngredient/searchFcRatio', {
              ingredientName: record.ingredientName,
              brand: this.model.brand
            }).then(res => {
              if (res.success) {
                this.$set(this.model.eneFormulaPgFrontIngredientDetails[0], 'fcRatio', res.result)
                this.computeFcRatio()
              }
            })
          }
          else {
            this.$set(this.model.eneFormulaPgFrontIngredientDetails[0], 'fcRatio', '')
          }
        }
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        //备份model原始值
        this.modelDefault = JSON.parse(JSON.stringify(this.model));
        if(this.disabled){
          this.isEdit = false;
        }else{
          this.isEdit = true;
        }
        this.visible = true;

      },
      submitForm () {
        const that = this;
        // 触发表单验证
        for(let i=0;i<this.model.eneFormulaPgFrontIngredientDetails.length;i++){
          if(this.model.eneFormulaPgFrontIngredientDetails[i].ingredientName===''){
            this.$message.error('请输入原料名称')
            return
          }
        }
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
    }
  }
</script>